/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2023-02-06 21:16:56
 * @LastEditors: Clark
 * @LastEditTime: 2023-02-06 21:35:00
 * @Description: file content
 */

#include "apue.h"
#include <netdb.h>
#include <errno.h>
#include <syslog.h>
#include <sys/socket.h>

#define BUFLEN 128
#define MAXADDRLEN 256

#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 256
#endif

extern int initserver(int, const struct sockaddr *, socklen_t, int);

void serve(int sockfd)
{
    int n = -1;
    socklen_t alen;
    FILE *fp = NULL;
    char buf[BUFLEN] = {0};
    char abuf[MAXADDRLEN] = {0};
    struct sockaddr *addr = (struct sockaddr *)abuf;

    set_cloexec(sockfd);
    while (1)
    {
        alen = MAXADDRLEN;
        if ((n = recvfrom(sockfd, buf, BUFLEN, 0, addr, &alen)) < 0)
        {
            syslog(LOG_ERR, "ruptimed: recvfrom error: %s", strerror(errno));
            exit(1);
        }

        if ((fp = popen("/usr/bin/uptime", "r")) == NULL)
        {
            sprintf(buf, "error: %s\n", strerror(errno));
            sendto(sockfd, buf, strlen(buf), 0, addr, alen);
        }
        else
        {
            if (fgets(buf, BUFLEN, fp) != NULL)
            {
                sendto(sockfd, buf, strlen(buf), 0, addr, alen);
            }
            pclose(fp);
        }
    }
}

int main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int sockfd, err, n;
    char *host;

    printf("%s %d\n", __func__, __LINE__);
    if (1 != argc)
    {
        err_quit("usage: ruptimed");
    }

    if ((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
    {
        n = HOST_NAME_MAX;
    }

    if ((host = malloc(n)) == NULL)
    {
        err_sys("malloc error");
    }

    if (gethostname(host, n) < 0)
    {
        err_sys("gethostname error");
    }

    printf("%s %d\n", __func__, __LINE__);
    daemonize("ruptimed");
    printf("%s %d\n", __func__, __LINE__);
    memset(&hint, 0, sizeof(hint));
    hint.ai_flags = AI_CANONNAME;
    hint.ai_socktype = SOCK_DGRAM;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;

    printf("%s %d\n", __func__, __LINE__);
    if ((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0)
    {
        syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s", gai_strerror(err));
        exit(1);
    }

    for (aip = ailist; aip != NULL; aip = aip->ai_next)
    {
        if ((sockfd = initserver(SOCK_DGRAM, aip->ai_addr, aip->ai_addrlen, 0)) >= 0)
        {
            serve(sockfd);
            printf("%s %d\n", __func__, __LINE__);
            exit(0);
        }
    }

    printf("%s %d\n", __func__, __LINE__);
    exit(1);
}
